package cn.bdqn.witcity.config;

import cn.bdqn.witcity.entity.Menu;
import cn.bdqn.witcity.entity.Role;
import cn.bdqn.witcity.service.MenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocation implements FilterInvocationSecurityMetadataSource {
   AntPathMatcher antPathMatcher=new AntPathMatcher();
   @Resource
   MenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
        String requestUrl=((FilterInvocation)obj).getRequestUrl();
        List<Menu> allMenus=menuService.getAllMenu();
        for(Menu menu:allMenus){
            if(antPathMatcher.match(menu.getUrl(),requestUrl)){
                List<Role> roles=menu.getRoles();
                String[] roleArray=new String[roles.size()];
                for(int i=0;i<roleArray.length;i++){
                    roleArray[i]=roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArray);

            }
        }

        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
